# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 教练表单

教练管理相关的表单定义
包括教练审核、编辑、搜索等表单
"""

from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import (
    StringField, TextAreaField, SelectField, IntegerField,
    DecimalField, BooleanField, HiddenField, ValidationError
)
from wtforms.validators import (
    DataRequired, Length, Email, NumberRange, Optional,
    Regexp
)
from flask_login import current_user
from sqlalchemy import and_, or_

from app.models.user import User
from app.models.campus import Campus


def safe_int_coerce(value):
    """
    安全的整数转换函数，用于处理 SelectField 的 coerce 参数
    能够处理空字符串、None 和数字字符串

    Args:
        value: 要转换的值

    Returns:
        int or None: 转换后的整数或 None
    """
    if value is None or value == '' or value == 'None':
        return None
    try:
        return int(value)
    except (ValueError, TypeError):
        return None


class CoachSearchForm(FlaskForm):
    """教练搜索表单"""

    keyword = StringField(
        '关键词',
        validators=[Optional(), Length(max=50)],
        render_kw={
            'placeholder': '搜索教练姓名、手机号...',
            'class': 'form-control'
        }
    )

    campus_id = SelectField(
        '所属校区',
        coerce=safe_int_coerce,
        choices=[],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    status = SelectField(
        '状态',
        choices=[
            ('', '全部状态'),
            ('pending', '待审核'),
            ('active', '在职'),
            ('inactive', '离职')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    coach_level = SelectField(
        '教练级别',
        choices=[
            ('', '全部级别'),
            ('senior', '高级教练'),
            ('middle', '中级教练'),
            ('junior', '初级教练')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    sort_by = SelectField(
        '排序方式',
        choices=[
            ('created_at_desc', '注册时间（新到旧）'),
            ('created_at_asc', '注册时间（旧到新）'),
            ('name_asc', '姓名（A-Z）'),
            ('name_desc', '姓名（Z-A）'),
            ('level_desc', '级别（高到低）'),
            ('rate_desc', '费用（高到低）'),
            ('rate_asc', '费用（低到高）')
        ],
        default='created_at_desc',
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 根据用户权限设置校区选择
        campus_choices = [('', '全部校区')]

        if current_user.is_authenticated:
            if current_user.is_super_admin():
                # 超级管理员可以看到所有校区
                campuses = Campus.query.all()  
                campus_choices.extend([(campus.id, campus.name) for campus in campuses])
            elif current_user.is_campus_admin():
                # 校区管理员只能看到自己的校区
                if current_user.campus_id:
                    campus = Campus.query.get(current_user.campus_id)
                    if campus:
                        campus_choices = [('', '全部校区'), (campus.id, campus.name)]

        self.campus_id.choices = campus_choices


class CoachEditForm(FlaskForm):
    """教练编辑表单"""

    real_name = StringField(
        '真实姓名',
        validators=[
            DataRequired(message='请输入真实姓名'),
            Length(2, 50, message='姓名长度必须在2-50个字符之间')
        ],
        render_kw={
            'placeholder': '请输入真实姓名',
            'class': 'form-control'
        }
    )

    phone = StringField(
        '手机号',
        validators=[
            DataRequired(message='请输入手机号'),
            Regexp(r'^1[3-9]\d{9}$', message='请输入正确的手机号格式')
        ],
        render_kw={
            'placeholder': '请输入11位手机号',
            'class': 'form-control'
        }
    )

    email = StringField(
        '邮箱',
        validators=[
            Optional(),
            Email(message='请输入正确的邮箱格式'),
            Length(max=100, message='邮箱长度不能超过100个字符')
        ],
        render_kw={
            'placeholder': '请输入邮箱地址（可选）',
            'class': 'form-control'
        }
    )

    gender = SelectField(
        '性别',
        choices=[
            ('', '请选择'),
            ('male', '男'),
            ('female', '女')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    age = IntegerField(
        '年龄',
        validators=[
            Optional(),
            NumberRange(min=18, max=80, message='年龄必须在18-80之间')
        ],
        render_kw={
            'placeholder': '请输入年龄',
            'class': 'form-control',
            'min': '18',
            'max': '80'
        }
    )

    campus_id = SelectField(
        '所属校区',
        coerce=safe_int_coerce,
        choices=[],
        validators=[DataRequired(message='请选择所属校区')],
        render_kw={'class': 'form-select'}
    )

    coach_level = SelectField(
        '教练级别',
        choices=[
            ('', '请选择'),
            ('senior', '高级教练'),
            ('middle', '中级教练'),
            ('junior', '初级教练')
        ],
        validators=[DataRequired(message='请选择教练级别')],
        render_kw={'class': 'form-select'}
    )

    hourly_rate = DecimalField(
        '每小时费用（元）',
        validators=[
            DataRequired(message='请输入每小时费用'),
            NumberRange(min=10, max=500, message='费用必须在10-500元之间')
        ],
        render_kw={
            'placeholder': '请输入每小时费用',
            'class': 'form-control',
            'step': '0.01',
            'min': '10',
            'max': '500'
        }
    )

    bio = TextAreaField(
        '个人简介',
        validators=[
            Optional(),
            Length(max=500, message='个人简介不能超过500个字符')
        ],
        render_kw={
            'placeholder': '请输入个人简介，介绍教学理念、专长等',
            'class': 'form-control',
            'rows': '4'
        }
    )

    experience = TextAreaField(
        '教学经验',
        validators=[
            Optional(),
            Length(max=1000, message='教学经验不能超过1000个字符')
        ],
        render_kw={
            'placeholder': '请详细描述教学经验、获得的荣誉、专业资质等',
            'class': 'form-control',
            'rows': '5'
        }
    )

    photo = FileField(
        '头像',
        validators=[
            Optional(),
            FileAllowed(['jpg', 'jpeg', 'png', 'gif'], '只允许上传图片文件')
        ],
        render_kw={'class': 'form-control'}
    )

    status = SelectField(
        '状态',
        choices=[
            ('active', '在职'),
            ('inactive', '离职')
        ],
        validators=[DataRequired(message='请选择状态')],
        render_kw={'class': 'form-select'}
    )

    def __init__(self, coach=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.coach = coach

        # 根据用户权限设置校区选择
        if current_user.is_authenticated:
            if current_user.is_super_admin():
                # 超级管理员可以选择所有校区
                campuses = Campus.query.all()  
                self.campus_id.choices = [(campus.id, campus.name) for campus in campuses]
            elif current_user.is_campus_admin():
                # 校区管理员只能选择自己的校区
                if current_user.campus_id:
                    campus = Campus.query.get(current_user.campus_id)
                    if campus:
                        self.campus_id.choices = [(campus.id, campus.name)]
                    else:
                        self.campus_id.choices = []
                else:
                    self.campus_id.choices = []

    def validate_phone(self, field):
        """验证手机号唯一性"""
        user = User.query.filter_by(phone=field.data).first()
        if user and (not self.coach or user.id != self.coach.id):
            raise ValidationError('该手机号已被注册')

    def validate_email(self, field):
        """验证邮箱唯一性"""
        if field.data:
            user = User.query.filter_by(email=field.data).first()
            if user and (not self.coach or user.id != self.coach.id):
                raise ValidationError('该邮箱已被注册')

    def validate_campus_id(self, field):
        """验证校区权限"""
        if current_user.is_campus_admin() and current_user.campus_id != field.data:
            raise ValidationError('您只能设置教练到自己管理的校区')


class CoachApprovalForm(FlaskForm):
    """教练审核表单"""

    coach_id = HiddenField(
        '教练ID',
        validators=[DataRequired()]
    )

    action = SelectField(
        '审核动作',
        choices=[
            ('approve', '通过'),
            ('reject', '拒绝')
        ],
        validators=[DataRequired(message='请选择审核动作')],
        render_kw={'class': 'form-select'}
    )

    campus_id = SelectField(
        '分配校区',
        coerce=safe_int_coerce,
        choices=[],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    coach_level = SelectField(
        '教练级别',
        choices=[
            ('junior', '初级教练'),
            ('middle', '中级教练'),
            ('senior', '高级教练')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    hourly_rate = DecimalField(
        '每小时费用（元）',
        validators=[
            Optional(),
            NumberRange(min=10, max=500, message='费用必须在10-500元之间')
        ],
        render_kw={
            'placeholder': '请输入每小时费用',
            'class': 'form-control',
            'step': '0.01'
        }
    )

    response_note = TextAreaField(
        '审核备注',
        validators=[
            Optional(),
            Length(max=255, message='备注不能超过255个字符')
        ],
        render_kw={
            'placeholder': '请输入审核意见或备注信息',
            'class': 'form-control',
            'rows': '3'
        }
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 根据用户权限设置校区选择
        campus_choices = [('', '请选择校区')]

        if current_user.is_authenticated:
            if current_user.is_super_admin():
                # 超级管理员可以分配到所有校区
                campuses = Campus.query.all()  
                campus_choices.extend([(campus.id, campus.name) for campus in campuses])
            elif current_user.is_campus_admin():
                # 校区管理员只能分配到自己的校区
                if current_user.campus_id:
                    campus = Campus.query.get(current_user.campus_id)
                    if campus:
                        campus_choices = [('', '请选择校区'), (campus.id, campus.name)]

        self.campus_id.choices = campus_choices


class CoachProfileForm(FlaskForm):
    """教练档案编辑表单（教练自己使用）"""

    bio = TextAreaField(
        '个人简介',
        validators=[
            Optional(),
            Length(max=500, message='个人简介不能超过500个字符')
        ],
        render_kw={
            'placeholder': '请输入个人简介，介绍教学理念、专长等',
            'class': 'form-control',
            'rows': '4'
        }
    )

    experience = TextAreaField(
        '教学经验',
        validators=[
            Optional(),
            Length(max=1000, message='教学经验不能超过1000个字符')
        ],
        render_kw={
            'placeholder': '请详细描述教学经验、获得的荣誉、专业资质等',
            'class': 'form-control',
            'rows': '5'
        }
    )

    photo = FileField(
        '头像',
        validators=[
            Optional(),
            FileAllowed(['jpg', 'jpeg', 'png', 'gif'], '只允许上传图片文件')
        ],
        render_kw={'class': 'form-control'}
    )


class CoachBatchForm(FlaskForm):
    """教练批量操作表单"""

    coach_ids = HiddenField(
        '教练ID列表',
        validators=[DataRequired(message='请选择要操作的教练')]
    )

    action = SelectField(
        '批量操作',
        choices=[
            ('', '请选择操作'),
            ('activate', '批量激活'),
            ('deactivate', '批量停用'),
            ('delete', '批量删除'),
            ('set_level', '设置级别'),
            ('transfer_campus', '转移校区')
        ],
        validators=[DataRequired(message='请选择批量操作类型')],
        render_kw={'class': 'form-select'}
    )

    target_campus_id = SelectField(
        '目标校区',
        coerce=safe_int_coerce,
        choices=[],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    target_level = SelectField(
        '目标级别',
        choices=[
            ('', '请选择'),
            ('senior', '高级教练'),
            ('middle', '中级教练'),
            ('junior', '初级教练')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 根据用户权限设置校区选择
        campus_choices = [('', '请选择校区')]

        if current_user.is_authenticated:
            if current_user.is_super_admin():
                campuses = Campus.query.all()  
                campus_choices.extend([(campus.id, campus.name) for campus in campuses])
            elif current_user.is_campus_admin():
                if current_user.campus_id:
                    campus = Campus.query.get(current_user.campus_id)
                    if campus:
                        campus_choices = [('', '请选择校区'), (campus.id, campus.name)]

        self.target_campus_id.choices = campus_choices


class CoachDeleteForm(FlaskForm):
    """教练删除确认表单"""

    coach_id = HiddenField(
        '教练ID',
        validators=[DataRequired()]
    )

    confirm_text = StringField(
        '确认删除',
        validators=[
            DataRequired(message='请输入确认文本')
        ],
        render_kw={
            'placeholder': '请输入"确认删除"',
            'class': 'form-control'
        }
    )

    def validate_confirm_text(self, field):
        """验证确认文本"""
        if field.data != '确认删除':
            raise ValidationError('请输入正确的确认文本：确认删除')